
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>applyMiddleware · GitBook</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.2">
        
        
        
    
    <link rel="stylesheet" href="../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
        

    

    
        
    
        
    
        
    
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="bindActionCreators.html" />
    
    
    <link rel="prev" href="combineReducers.html" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        
    
        <li class="chapter " data-level="1.1" data-path="../">
            
                <a href="../">
            
                    
                    Read Me
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="../introduction/">
            
                <a href="../introduction/">
            
                    
                    Introduction
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.2.1" data-path="../introduction/Motivation.html">
            
                <a href="../introduction/Motivation.html">
            
                    
                    Motivation
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.2" data-path="../introduction/CoreConcepts.html">
            
                <a href="../introduction/CoreConcepts.html">
            
                    
                    Core Concepts
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.3" data-path="../introduction/ThreePrinciples.html">
            
                <a href="../introduction/ThreePrinciples.html">
            
                    
                    Three Principles
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.4" data-path="../introduction/PriorArt.html">
            
                <a href="../introduction/PriorArt.html">
            
                    
                    Prior Art
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.5" data-path="../introduction/Ecosystem.html">
            
                <a href="../introduction/Ecosystem.html">
            
                    
                    Ecosystem
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.6" data-path="../introduction/Examples.html">
            
                <a href="../introduction/Examples.html">
            
                    
                    Examples
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.3" data-path="../basics/">
            
                <a href="../basics/">
            
                    
                    Basics
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.3.1" data-path="../basics/Actions.html">
            
                <a href="../basics/Actions.html">
            
                    
                    Actions
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.2" data-path="../basics/Reducers.html">
            
                <a href="../basics/Reducers.html">
            
                    
                    Reducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.3" data-path="../basics/Store.html">
            
                <a href="../basics/Store.html">
            
                    
                    Store
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.4" data-path="../basics/DataFlow.html">
            
                <a href="../basics/DataFlow.html">
            
                    
                    Data Flow
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.5" data-path="../basics/UsageWithReact.html">
            
                <a href="../basics/UsageWithReact.html">
            
                    
                    Usage with React
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.6" data-path="../basics/ExampleTodoList.html">
            
                <a href="../basics/ExampleTodoList.html">
            
                    
                    Example: Todo List
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.4" data-path="../advanced/">
            
                <a href="../advanced/">
            
                    
                    Advanced
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.4.1" data-path="../advanced/AsyncActions.html">
            
                <a href="../advanced/AsyncActions.html">
            
                    
                    Async Actions
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.2" data-path="../advanced/AsyncFlow.html">
            
                <a href="../advanced/AsyncFlow.html">
            
                    
                    Async Flow
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.3" data-path="../advanced/Middleware.html">
            
                <a href="../advanced/Middleware.html">
            
                    
                    Middleware
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.4" data-path="../advanced/UsageWithReactRouter.html">
            
                <a href="../advanced/UsageWithReactRouter.html">
            
                    
                    Usage with React Router
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.5" data-path="../advanced/ExampleRedditAPI.html">
            
                <a href="../advanced/ExampleRedditAPI.html">
            
                    
                    Example: Reddit API
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.6" >
            
                <span>
            
                    
                    Next Steps
            
                </span>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.5" data-path="../recipes/">
            
                <a href="../recipes/">
            
                    
                    Recipes
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.5.1" data-path="../recipes/MigratingToRedux.html">
            
                <a href="../recipes/MigratingToRedux.html">
            
                    
                    Migrating to Redux
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.2" data-path="../recipes/UsingObjectSpreadOperator.html">
            
                <a href="../recipes/UsingObjectSpreadOperator.html">
            
                    
                    Using Object Spread Operator
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.3" data-path="../recipes/ReducingBoilerplate.html">
            
                <a href="../recipes/ReducingBoilerplate.html">
            
                    
                    Reducing Boilerplate
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.4" data-path="../recipes/ServerRendering.html">
            
                <a href="../recipes/ServerRendering.html">
            
                    
                    Server Rendering
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.5" data-path="../recipes/WritingTests.html">
            
                <a href="../recipes/WritingTests.html">
            
                    
                    Writing Tests
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.6" data-path="../recipes/ComputingDerivedData.html">
            
                <a href="../recipes/ComputingDerivedData.html">
            
                    
                    Computing Derived Data
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.7" data-path="../recipes/ImplementingUndoHistory.html">
            
                <a href="../recipes/ImplementingUndoHistory.html">
            
                    
                    Implementing Undo History
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.8" data-path="../recipes/IsolatingSubapps.html">
            
                <a href="../recipes/IsolatingSubapps.html">
            
                    
                    Isolating Subapps
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9" data-path="../recipes/StructuringReducers.html">
            
                <a href="../recipes/StructuringReducers.html">
            
                    
                    Structuring Reducers
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.5.9.1" data-path="../recipes/reducers/PrerequisiteConcepts.html">
            
                <a href="../recipes/reducers/PrerequisiteConcepts.html">
            
                    
                    Prerequisite Concepts
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.2" data-path="../recipes/reducers/BasicReducerStructure.html">
            
                <a href="../recipes/reducers/BasicReducerStructure.html">
            
                    
                    Basic Reducer Structure
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.3" data-path="../recipes/reducers/SplittingReducerLogic.html">
            
                <a href="../recipes/reducers/SplittingReducerLogic.html">
            
                    
                    Splitting Reducer Logic
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.4" data-path="../recipes/reducers/RefactoringReducersExample.html">
            
                <a href="../recipes/reducers/RefactoringReducersExample.html">
            
                    
                    Refactoring Reducers Example
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.5" data-path="../recipes/reducers/UsingCombineReducers.html">
            
                <a href="../recipes/reducers/UsingCombineReducers.html">
            
                    
                    Using combineReducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.6" data-path="../recipes/reducers/BeyondCombineReducers.html">
            
                <a href="../recipes/reducers/BeyondCombineReducers.html">
            
                    
                    Beyond combineReducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.7" data-path="../recipes/reducers/NormalizingStateShape.html">
            
                <a href="../recipes/reducers/NormalizingStateShape.html">
            
                    
                    Normalizing State Shape
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.8" data-path="../recipes/reducers/UpdatingNormalizedData.html">
            
                <a href="../recipes/reducers/UpdatingNormalizedData.html">
            
                    
                    Updating Normalized Data
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.9" data-path="../recipes/reducers/ReusingReducerLogic.html">
            
                <a href="../recipes/reducers/ReusingReducerLogic.html">
            
                    
                    Reusing Reducer Logic
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.10" data-path="../recipes/reducers/ImmutableUpdatePatterns.html">
            
                <a href="../recipes/reducers/ImmutableUpdatePatterns.html">
            
                    
                    Immutable Update Patterns
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.11" data-path="../recipes/reducers/InitializingState.html">
            
                <a href="../recipes/reducers/InitializingState.html">
            
                    
                    Initializing State
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.5.10" data-path="../recipes/UsingImmutableJS.html">
            
                <a href="../recipes/UsingImmutableJS.html">
            
                    
                    Using Immutable.JS with Redux
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.6" data-path="../FAQ.html">
            
                <a href="../FAQ.html">
            
                    
                    FAQ
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.6.1" data-path="../faq/General.html">
            
                <a href="../faq/General.html">
            
                    
                    General
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.2" data-path="../faq/Reducers.html">
            
                <a href="../faq/Reducers.html">
            
                    
                    Reducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.3" data-path="../faq/OrganizingState.html">
            
                <a href="../faq/OrganizingState.html">
            
                    
                    Organizing State
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.4" data-path="../faq/StoreSetup.html">
            
                <a href="../faq/StoreSetup.html">
            
                    
                    Store Setup
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.5" data-path="../faq/Actions.html">
            
                <a href="../faq/Actions.html">
            
                    
                    Actions
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.6" data-path="../faq/ImmutableData.html">
            
                <a href="../faq/ImmutableData.html">
            
                    
                    Immutable Data
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.7" data-path="../faq/CodeStructure.html">
            
                <a href="../faq/CodeStructure.html">
            
                    
                    Code Structure
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.8" data-path="../faq/Performance.html">
            
                <a href="../faq/Performance.html">
            
                    
                    Performance
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.9" data-path="../faq/ReactRedux.html">
            
                <a href="../faq/ReactRedux.html">
            
                    
                    React Redux
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.10" data-path="../faq/Miscellaneous.html">
            
                <a href="../faq/Miscellaneous.html">
            
                    
                    Miscellaneous
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.7" data-path="../Troubleshooting.html">
            
                <a href="../Troubleshooting.html">
            
                    
                    Troubleshooting
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.8" data-path="../Glossary.html">
            
                <a href="../Glossary.html">
            
                    
                    Glossary
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9" data-path="./">
            
                <a href="./">
            
                    
                    API Reference
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.9.1" data-path="createStore.html">
            
                <a href="createStore.html">
            
                    
                    createStore
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.2" data-path="Store.html">
            
                <a href="Store.html">
            
                    
                    Store
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.3" data-path="combineReducers.html">
            
                <a href="combineReducers.html">
            
                    
                    combineReducers
            
                </a>
            

            
        </li>
    
        <li class="chapter active" data-level="1.9.4" data-path="applyMiddleware.html">
            
                <a href="applyMiddleware.html">
            
                    
                    applyMiddleware
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.5" data-path="bindActionCreators.html">
            
                <a href="bindActionCreators.html">
            
                    
                    bindActionCreators
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.6" data-path="compose.html">
            
                <a href="compose.html">
            
                    
                    compose
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.10" data-path="../CHANGELOG.md">
            
                <span>
            
                    
                    Change Log
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.11" data-path="../PATRONS.md">
            
                <span>
            
                    
                    Patrons
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.12" data-path="../Feedback.html">
            
                <a href="../Feedback.html">
            
                    
                    Feedback
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href=".." >applyMiddleware</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="applymiddlewaremiddleware"><code>applyMiddleware(...middleware)</code></h1>
<p><a href="../Glossary.html#middleware" class="glossary-term" title="">Middleware</a> is the suggested way to extend Redux with custom functionality. <a href="../Glossary.html#middleware" class="glossary-term" title="">Middleware</a> lets you wrap the <a href="../Glossary.html#store" class="glossary-term" title="">store</a>&apos;s <a href="Store.html#dispatch"><code>dispatch</code></a> method for fun and profit. The key feature of <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> is that it is composable. Multiple <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> can be combined together, where each <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> requires no knowledge of what comes before or after it in the chain.</p>
<p>The most common use case for <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> is to support asynchronous actions without much boilerplate code or a dependency on a library like <a href="https://github.com/Reactive-Extensions/RxJS" target="_blank">Rx</a>. It does so by letting you dispatch <a href="../Glossary.html#async-action">async actions</a> in addition to normal actions.</p>
<p>For example, <a href="https://github.com/gaearon/redux-thunk" target="_blank">redux-thunk</a> lets the <a href="../Glossary.html#action" class="glossary-term" title="">action</a> creators invert control by dispatching functions. They would receive <a href="Store.html#dispatch"><code>dispatch</code></a> as an argument and may call it asynchronously. Such functions are called <em>thunks</em>. Another example of <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> is <a href="https://github.com/acdlite/redux-promise" target="_blank">redux-promise</a>. It lets you dispatch a <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise" target="_blank">Promise</a> async <a href="../Glossary.html#action" class="glossary-term" title="">action</a>, and dispatches a normal <a href="../Glossary.html#action" class="glossary-term" title="">action</a> when the Promise resolves.</p>
<p><a href="../Glossary.html#middleware" class="glossary-term" title="">Middleware</a> is not baked into <a href="createStore.html"><code>createStore</code></a> and is not a fundamental part of the Redux architecture, but we consider it useful enough to be supported right in the core. This way, there is a single standard way to extend <a href="Store.html#dispatch"><code>dispatch</code></a> in the ecosystem, and different <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> may compete in expressiveness and utility.</p>
<h4 id="arguments">Arguments</h4>
<ul>
<li><code>...middleware</code> (<em>arguments</em>): Functions that conform to the Redux <em><a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> API</em>. Each <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> receives <a href="Store.html"><code>Store</code></a>&apos;s <a href="Store.html#dispatch"><code>dispatch</code></a> and <a href="Store.html#getState"><code>getState</code></a> functions as named arguments, and returns a function. That function will be given the <code>next</code> <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a>&apos;s dispatch method, and is expected to return a function of <code>action</code> calling <code>next(action)</code> with a potentially different argument, or at a different time, or maybe not calling it at all. The last <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> in the chain will receive the real <a href="../Glossary.html#store" class="glossary-term" title="">store</a>&apos;s <a href="Store.html#dispatch"><code>dispatch</code></a> method as the <code>next</code> parameter, thus ending the chain. So, the <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> signature is <code>({ getState, dispatch }) =&gt; next =&gt; action</code>.</li>
</ul>
<h4 id="returns">Returns</h4>
<p>(<em>Function</em>) A <a href="../Glossary.html#store" class="glossary-term" title="">store</a> enhancer that applies the given <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a>. The <a href="../Glossary.html#store" class="glossary-term" title="">store</a> enhancer signature is <code>createStore =&gt; createStore&apos;</code> but the easiest way to apply it is to pass it to <a href="createStore.html"><code>createStore()</code></a> as the last <code>enhancer</code> argument.</p>
<h4 id="example-custom-logger-middleware">Example: Custom Logger Middleware</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createStore, applyMiddleware } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;redux&apos;</span>
<span class="hljs-keyword">import</span> todos <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;./reducers&apos;</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logger</span>(<span class="hljs-params">{ getState }</span>) </span>{
  <span class="hljs-keyword">return</span> (next) =&gt; (action) =&gt; {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&apos;will dispatch&apos;</span>, action)

    <span class="hljs-comment">// Call the next dispatch method in the middleware chain.</span>
    <span class="hljs-keyword">let</span> returnValue = next(action)

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&apos;state after dispatch&apos;</span>, getState())

    <span class="hljs-comment">// This will likely be the action itself, unless</span>
    <span class="hljs-comment">// a middleware further in chain changed it.</span>
    <span class="hljs-keyword">return</span> returnValue
  }
}

<span class="hljs-keyword">let</span> store = createStore(
  todos,
  [ <span class="hljs-string">&apos;Use Redux&apos;</span> ],
  applyMiddleware(logger)
)

store.dispatch({
  type: <span class="hljs-string">&apos;ADD_TODO&apos;</span>,
  text: <span class="hljs-string">&apos;Understand the middleware&apos;</span>
})
<span class="hljs-comment">// (These lines will be logged by the middleware:)</span>
<span class="hljs-comment">// will dispatch: { type: &apos;ADD_TODO&apos;, text: &apos;Understand the middleware&apos; }</span>
<span class="hljs-comment">// state after dispatch: [ &apos;Use Redux&apos;, &apos;Understand the middleware&apos; ]</span>
</code></pre>
<h4 id="example-using-thunk-middleware-for-async-actions">Example: Using Thunk Middleware for Async Actions</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createStore, combineReducers, applyMiddleware } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;redux&apos;</span>
<span class="hljs-keyword">import</span> thunk <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;redux-thunk&apos;</span>
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> reducers <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;./reducers&apos;</span>

<span class="hljs-keyword">let</span> reducer = combineReducers(reducers)
<span class="hljs-comment">// applyMiddleware supercharges createStore with middleware:</span>
<span class="hljs-keyword">let</span> store = createStore(reducer, applyMiddleware(thunk))

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchSecretSauce</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">&apos;https://www.google.com/search?q=secret+sauce&apos;</span>)
}

<span class="hljs-comment">// These are the normal action creators you have seen so far.</span>
<span class="hljs-comment">// The actions they return can be dispatched without any middleware.</span>
<span class="hljs-comment">// However, they only express &#x201C;facts&#x201D; and not the &#x201C;async flow&#x201D;.</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">makeASandwich</span>(<span class="hljs-params">forPerson, secretSauce</span>) </span>{
  <span class="hljs-keyword">return</span> {
    type: <span class="hljs-string">&apos;MAKE_SANDWICH&apos;</span>,
    forPerson,
    secretSauce
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">apologize</span>(<span class="hljs-params">fromPerson, toPerson, error</span>) </span>{
  <span class="hljs-keyword">return</span> {
    type: <span class="hljs-string">&apos;APOLOGIZE&apos;</span>,
    fromPerson,
    toPerson,
    error
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withdrawMoney</span>(<span class="hljs-params">amount</span>) </span>{
  <span class="hljs-keyword">return</span> {
    type: <span class="hljs-string">&apos;WITHDRAW&apos;</span>,
    amount
  }
}

<span class="hljs-comment">// Even without middleware, you can dispatch an action:</span>
store.dispatch(withdrawMoney(<span class="hljs-number">100</span>))

<span class="hljs-comment">// But what do you do when you need to start an asynchronous action,</span>
<span class="hljs-comment">// such as an API call, or a router transition?</span>

<span class="hljs-comment">// Meet thunks.</span>
<span class="hljs-comment">// A thunk is a function that returns a function.</span>
<span class="hljs-comment">// This is a thunk.</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">makeASandwichWithSecretSauce</span>(<span class="hljs-params">forPerson</span>) </span>{

  <span class="hljs-comment">// Invert control!</span>
  <span class="hljs-comment">// Return a function that accepts `dispatch` so we can dispatch later.</span>
  <span class="hljs-comment">// Thunk middleware knows how to turn thunk async actions into actions.</span>

  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">dispatch</span>) </span>{
    <span class="hljs-keyword">return</span> fetchSecretSauce().then(
      sauce =&gt; dispatch(makeASandwich(forPerson, sauce)),
      error =&gt; dispatch(apologize(<span class="hljs-string">&apos;The Sandwich Shop&apos;</span>, forPerson, error))
    )
  }
}

<span class="hljs-comment">// Thunk middleware lets me dispatch thunk async actions</span>
<span class="hljs-comment">// as if they were actions!</span>

store.dispatch(
  makeASandwichWithSecretSauce(<span class="hljs-string">&apos;Me&apos;</span>)
)

<span class="hljs-comment">// It even takes care to return the thunk&apos;s return value</span>
<span class="hljs-comment">// from the dispatch, so I can chain Promises as long as I return them.</span>

store.dispatch(
  makeASandwichWithSecretSauce(<span class="hljs-string">&apos;My wife&apos;</span>)
).then(() =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&apos;Done!&apos;</span>)
})

<span class="hljs-comment">// In fact I can write action creators that dispatch</span>
<span class="hljs-comment">// actions and async actions from other action creators,</span>
<span class="hljs-comment">// and I can build my control flow with Promises.</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">makeSandwichesForEverybody</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">dispatch, getState</span>) </span>{
    <span class="hljs-keyword">if</span> (!getState().sandwiches.isShopOpen) {

      <span class="hljs-comment">// You don&apos;t have to return Promises, but it&apos;s a handy convention</span>
      <span class="hljs-comment">// so the caller can always call .then() on async dispatch result.</span>

      <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.resolve()
    }

    <span class="hljs-comment">// We can dispatch both plain object actions and other thunks,</span>
    <span class="hljs-comment">// which lets us compose the asynchronous actions in a single flow.</span>

    <span class="hljs-keyword">return</span> dispatch(
      makeASandwichWithSecretSauce(<span class="hljs-string">&apos;My Grandma&apos;</span>)
    ).then(() =&gt;
      <span class="hljs-built_in">Promise</span>.all([
        dispatch(makeASandwichWithSecretSauce(<span class="hljs-string">&apos;Me&apos;</span>)),
        dispatch(makeASandwichWithSecretSauce(<span class="hljs-string">&apos;My wife&apos;</span>))
      ])
    ).then(() =&gt;
      dispatch(makeASandwichWithSecretSauce(<span class="hljs-string">&apos;Our kids&apos;</span>))
    ).then(() =&gt;
      dispatch(getState().myMoney &gt; <span class="hljs-number">42</span> ?
        withdrawMoney(<span class="hljs-number">42</span>) :
        apologize(<span class="hljs-string">&apos;Me&apos;</span>, <span class="hljs-string">&apos;The Sandwich Shop&apos;</span>)
      )
    )
  }
}

<span class="hljs-comment">// This is very useful for server side rendering, because I can wait</span>
<span class="hljs-comment">// until data is available, then synchronously render the app.</span>

<span class="hljs-keyword">import</span> { renderToString } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react-dom/server&apos;</span>

store.dispatch(
  makeSandwichesForEverybody()
).then(() =&gt;
  response.send(renderToString(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MyApp</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span> /&gt;</span>))
)

// I can also dispatch a thunk async action from a component
// any time its props change to load the missing data.

import { connect } from &apos;react-redux&apos;
import { Component } from &apos;react&apos;

class SandwichShop extends Component {
  componentDidMount() {
    this.props.dispatch(
      makeASandwichWithSecretSauce(this.props.forPerson)
    )
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.forPerson !== this.props.forPerson) {
      this.props.dispatch(
        makeASandwichWithSecretSauce(nextProps.forPerson)
      )
    }
  }

  render() {
    return <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{this.props.sandwiches.join(&apos;mustard&apos;)}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  }
}

export default connect(
  state =&gt; ({
    sandwiches: state.sandwiches
  })
)(SandwichShop)
</span></code></pre>
<h4 id="tips">Tips</h4>
<ul>
<li><p><a href="../Glossary.html#middleware" class="glossary-term" title="">Middleware</a> only wraps the <a href="../Glossary.html#store" class="glossary-term" title="">store</a>&apos;s <a href="Store.html#dispatch"><code>dispatch</code></a> function. Technically, anything a <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> can do, you can do manually by wrapping every <code>dispatch</code> call, but it&apos;s easier to manage this in a single place and define <a href="../Glossary.html#action" class="glossary-term" title="">action</a> transformations on the scale of the whole project.</p>
</li>
<li><p>If you use other <a href="../Glossary.html#store" class="glossary-term" title="">store</a> enhancers in addition to <code>applyMiddleware</code>, make sure to put <code>applyMiddleware</code> before them in the composition chain because the <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> is potentially asynchronous. For example, it should go before <a href="https://github.com/gaearon/redux-devtools" target="_blank">redux-devtools</a> because otherwise the DevTools won&apos;t see the raw actions emitted by the Promise <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> and such.</p>
</li>
<li><p>If you want to conditionally apply a <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a>, make sure to only import it when it&apos;s needed:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> middleware = [ a, b ]
<span class="hljs-keyword">if</span> (process.env.NODE_ENV !== <span class="hljs-string">&apos;production&apos;</span>) {
  <span class="hljs-keyword">let</span> c = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;some-debug-middleware&apos;</span>)
  <span class="hljs-keyword">let</span> d = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;another-debug-middleware&apos;</span>)
  middleware = [ ...middleware, c, d ]
}

<span class="hljs-keyword">const</span> store = createStore(
  reducer,
  preloadedState,
  applyMiddleware(...middleware)
)
</code></pre>
<p>This makes it easier for bundling tools to cut out unneeded modules and reduces the size of your builds.</p>
</li>
<li><p>Ever wondered what <code>applyMiddleware</code> itself is? It ought to be an extension mechanism more powerful than the <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> itself. Indeed, <code>applyMiddleware</code> is an example of the most powerful Redux extension mechanism called <a href="../Glossary.html#store-enhancer">store enhancers</a>. It is highly unlikely you&apos;ll ever want to write a <a href="../Glossary.html#store" class="glossary-term" title="">store</a> enhancer yourself. Another example of a <a href="../Glossary.html#store" class="glossary-term" title="">store</a> enhancer is <a href="https://github.com/gaearon/redux-devtools" target="_blank">redux-devtools</a>. <a href="../Glossary.html#middleware" class="glossary-term" title="">Middleware</a> is less powerful than a <a href="../Glossary.html#store" class="glossary-term" title="">store</a> enhancer, but it is easier to write.</p>
</li>
<li><p><a href="../Glossary.html#middleware" class="glossary-term" title="">Middleware</a> sounds much more complicated than it really is. The only way to really understand <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> is to see how the existing <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> works, and try to write your own. The function nesting can be intimidating, but most of the <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> you&apos;ll find are, in fact, 10-liners, and the nesting and composability is what makes the <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> system powerful.</p>
</li>
<li><p>To apply multiple <a href="../Glossary.html#store" class="glossary-term" title="">store</a> enhancers, you may use <a href="compose.html"><code>compose()</code></a>.</p>
</li>
</ul>

                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="combineReducers.html" class="navigation navigation-prev " aria-label="Previous page: combineReducers">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
                <a href="bindActionCreators.html" class="navigation navigation-next " aria-label="Next page: bindActionCreators">
                    <i class="fa fa-angle-right"></i>
                </a>
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"applyMiddleware","level":"1.9.4","depth":2,"next":{"title":"bindActionCreators","level":"1.9.5","depth":2,"path":"api/bindActionCreators.md","ref":"./api/bindActionCreators.md","articles":[]},"previous":{"title":"combineReducers","level":"1.9.3","depth":2,"path":"api/combineReducers.md","ref":"./api/combineReducers.md","articles":[]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":["livereload"],"pluginsConfig":{"livereload":{},"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"}},"file":{"path":"api/applyMiddleware.md","mtime":"2017-03-13T14:28:11.303Z","type":"markdown"},"gitbook":{"version":"3.2.2","time":"2017-03-15T14:47:19.389Z"},"basePath":"..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../gitbook/gitbook.js"></script>
    <script src="../gitbook/theme.js"></script>
    
        
        <script src="../gitbook/gitbook-plugin-livereload/plugin.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    

    </body>
</html>

